#include <stdio.h>
#include <stdlib.h>


int key_size = 8;
int crypt_size = 32;

//returns int 1 if the element already exists
int check_existence(int *array, int number) {
	
	for (int i=0; i<crypt_size; i++) {
		if (array[i] == number) 
			return 1;
         }
         return 0;
}

//returns free index 
int find_empty_index(int *array) {
	
	for (int i=0; i<crypt_size; i++) {
		if (array[i] == crypt_size) return i;
	}
	return 32;
}

//Fills the first elements based on the key 
void first_fill(char *key_array, int *crypted_array) {
	
	int key_c;
	for (int i=0; i<key_size; i++) {
        	key_c = (int)key_array[i]%crypt_size;
        	if (!check_existence(crypted_array, key_c)) 
                	crypted_array[find_empty_index(crypted_array)] = key_c;
	}
}

//Number of free indexes, 0 if all are filled
int count_of_empty_bits(int *array) {
	int count=0;
	for (int i=0; i<crypt_size; i++) {
		if (array[i] == crypt_size) count++;
	}
	return count;
}

//Total count of elements a[0]+..+a[31]
int sum_of_elements(int *array) {
        int count=0;
        for (int i=0; i<crypt_size; i++) 
                count+=array[i];
        return count;
}


int main() {


	char key[key_size];
	sprintf(key, "0_03d0A-");

	int cr_array[crypt_size];

	for (int j=0; j<crypt_size; j++)
		cr_array[j] = crypt_size; //Fill the array

	first_fill(key, cr_array);
	for (int j=0; j<crypt_size; j++)
        printf("%d ", cr_array[j]);
	//printf("Initializing finished\n");	
	//int iteration = 0;
	int new_key;
	int a_key;
	int add=0;

	while (true) {
		if(!count_of_empty_bits(cr_array)) break;
				
		a_key=sum_of_elements(cr_array)+ count_of_empty_bits(cr_array) + crypt_size + add;
		new_key=a_key%32;
		if (!check_existence(cr_array, new_key)) {
			cr_array[find_empty_index(cr_array)] = new_key;
			//printf("success iteration=%d key=%d a_key=%d\n", ++iteration, new_key, a_key);
			add+=1;	
		} else	
		//printf("\tfailed iteration=%d key=%d a_key=%d\n", ++iteration, new_key, a_key);
		add+=7;
	}


printf("\n\n\n");
for (int j=0; j<crypt_size; j++)
	printf("%d ", cr_array[j]);
printf("\n");
}

